package com.handu.luna.core.domain.promotion;

import java.util.Date;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.handu.luna.core.domain.BaseRepository;

public interface SecKillGroupBuyGoodsRepository extends JpaRepository<SecKillGroupBuyGoods,Long>,BaseRepository<SecKillGroupBuyGoods>,JpaSpecificationExecutor<SecKillGroupBuyGoods>{
	
	@Query("from SecKillGroupBuyGoods s  where s.secKillGroupBuyId = :secKillGroupBuyId")
	Page<SecKillGroupBuyGoods> findBySecKillGroupBuyId(@Param("secKillGroupBuyId") int secKillGroupBuyId,Pageable pageable);
	
	@Query("from SecKillGroupBuyGoods s  where s.secKillGroupBuyId = :secKillGroupBuyId AND goodsId = :goodsId ")
	List<SecKillGroupBuyGoods> findBySecKillGroupBuyIdAndGoodsId(@Param("secKillGroupBuyId") int secKillGroupBuyId,@Param("goodsId") long goodsId);
	
	@Modifying
	@Query("delete from SecKillGroupBuyGoods s  where s.secKillGroupBuyId = :secKillGroupBuyId")
	public void deleteBySecKillGroupBuyId(@Param("secKillGroupBuyId") int secKillGroupBuyId);
	
	@Modifying
	@Query("delete from SecKillGroupBuyGoods s  where s.secKillGroupBuyId = :secKillGroupBuyId and s.goodsId = :goodsId")
	public void deleteBySecKillGroupBuyIdAndGoodsId(@Param("secKillGroupBuyId") int secKillGroupBuyId,@Param("goodsId") long goodsId);


    /************************************商品详情页---开始*************************************************/

    @Query("select s2 from SecKillGroupBuy s2 " +
                "where s2.beginTime <= ?2 and s2.endTime >= ?2 and " +
                "s2.id in (select s.secKillGroupBuyId from SecKillGroupBuyGoods s where s.goodsId = ?1)")
    public SecKillGroupBuy findCurrentSecKillGroupBuyByGoodsId(long goodsId,Date date);

    @Query("select s2 from SecKillGroupBuy s2 " +
                "where s2.beginTime >= ?2 and " +
                "s2.id in (select s.secKillGroupBuyId from SecKillGroupBuyGoods s where s.goodsId = ?1)")
    public SecKillGroupBuy findUnActivatedSecKillGroupBuyByGoodsId(long goodsId,Date date);

    @Query("select s2 from SecKillGroupBuy s2 where ?1 >= s2.beginTime and  ?1 <= s2.endTime")
    public List<SecKillGroupBuy> findActive(Date date);

    @Query("select s from SecKillGroupBuyGoods s  where s.secKillGroupBuyId = ?1 AND goodsId = ?2 ")
	SecKillGroupBuyGoods findCurrentSecKillGroupBuyGoodsIdAndGoodsId(int secKillGroupBuyId,long goodsId);


    /************************************商品详情页---结束*************************************************/
}
